package com.wanbatv.wangwangba;

import android.app.AlertDialog;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wangwangba.util.Behavior;
import com.wanbatv.wangwangba.util.FocusImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;




public class MainActivity extends MonitorActivity implements MediaPlayer.OnPreparedListener,MediaPlayer.OnCompletionListener,SurfaceHolder.Callback{
    private long exitTime=0;
    private SurfaceView surfaceView;
    MediaPlayer mediaPlay;
    SurfaceHolder surfaceholder;
    private AlertDialog myDialog = null;

    private FocusImageView main_button_down;
    private FocusImageView main_button_show;
    private RelativeLayout main_lin_down;

    private FocusImageView zonghe_iv;
    private FocusImageView xiuxian_iv;
    private FocusImageView yundong_iv;
    private FocusImageView zhanshi_iv;

    private FocusImageView zonghe_iv1;
    private FocusImageView xiuxian_iv1;
    private FocusImageView yundong_iv1;
    private FocusImageView zhanshi_iv1;

    private FocusImageView dogtv_iv;
    private FocusImageView faq_iv;

    private ImageView mian_title_iv;

    private RelativeLayout main_rela_up;
    int BOFANG_NUM=0;
    int PINGDAO_NUM=0;
    String url=null;
    private static final int MSG_PLAY_PROGRESS = 1;
    private static final int PLAY_MESSAGE=2;
    private static final int MSG_UP_DOWN=3;

    private ImageView loading1;
    private ImageView loading2;

    private ImageView daiji_iv;

    List<JSONObject> list=new ArrayList<JSONObject>();

    private Boolean IS_DOWN=false;
    private boolean IS_DOGTV=false;

    private String url_qian="http://121.201.7.173:8087/api/wangwangba/program/";
    private String TOKEN=null;

    private int content_code;
    private String content_name=null;

    Handler mHandler = new Handler(Looper.getMainLooper()) {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_PLAY_PROGRESS:
                    if(loading1.getVisibility()==View.VISIBLE || loading2.getVisibility()==View.VISIBLE){

                            if (loading1.getVisibility() == View.VISIBLE) {
                                loading1.setVisibility(View.GONE);
                                loading2.setVisibility(View.VISIBLE);
                            } else {
                                loading1.setVisibility(View.VISIBLE);
                                loading2.setVisibility(View.GONE);
                            }

                    }

                    mHandler.removeMessages(MSG_PLAY_PROGRESS);
                    mHandler.sendEmptyMessageDelayed(MSG_PLAY_PROGRESS, 500);
                    break;
                case PLAY_MESSAGE:
                    if(loading1.getVisibility()==View.VISIBLE || loading2.getVisibility()==View.VISIBLE) {
                        try {
                            if(mediaPlay.isPlaying()) {
                                if (mediaPlay.getCurrentPosition() > 0) {
                                    loading1.setVisibility(View.GONE);
                                    loading2.setVisibility(View.GONE);
                                }
                            }
                        } catch (IllegalStateException e) {

                        }
                    }
                    mHandler.removeMessages(PLAY_MESSAGE);
                    mHandler.sendEmptyMessageDelayed(PLAY_MESSAGE, 500);
                    break;
                case MSG_UP_DOWN:
//                    if(!myDialog.isShowing()) {
                        if (!IS_DOWN) {
                            IS_DOWN = true;
                        } else {
                            main_lin_down.setVisibility(View.GONE);
//                            main_button_show.setVisibility(View.VISIBLE);
                            main_button_show.requestFocus();
                        }
//                    }
                    mHandler.removeMessages(MSG_UP_DOWN);
                    mHandler.sendEmptyMessageDelayed(MSG_UP_DOWN, 3500);
                    break;

            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //屏幕常亮
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        surfaceView=(SurfaceView)findViewById(R.id.surfaceview);
        surfaceholder = surfaceView.getHolder();
        surfaceholder.setFixedSize(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        surfaceholder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        surfaceholder.addCallback(this);

        loading1=(ImageView)this.findViewById(R.id.loading1);
        loading2=(ImageView)this.findViewById(R.id.loading2);

        main_button_down=(FocusImageView) findViewById(R.id.main_button_down);
        main_button_show=(FocusImageView)findViewById(R.id.main_button_show);
        main_lin_down=(RelativeLayout)findViewById(R.id.main_lin_down);
        main_rela_up=(RelativeLayout)findViewById(R.id.main_rela_up);

        daiji_iv=(ImageView)findViewById(R.id.daiji_iv);

        main_button_down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                main_rela_up.setVisibility(View.GONE);
                main_lin_down.setVisibility(View.GONE);
                main_button_show.setVisibility(View.VISIBLE);
                main_button_show.requestFocus();
                Behavior.onEvent(MainActivity.this, 3020001, "点击隐藏频道栏");

            }
        });
        main_button_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                main_rela_up.setVisibility(View.VISIBLE);
                main_lin_down.setVisibility(View.VISIBLE);
                main_button_show.setVisibility(View.GONE);
                main_button_down.requestFocus();
                Behavior.onEvent(MainActivity.this, 3020002, "点击展开频道栏");
            }
        });

//        dogtv_iv=(FocusImageView)findViewById(R.id.dogtv_iv);
//        dogtv_iv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                PINGDAO_NUM=5;
//                Behavior.onEvent(MainActivity.this, 3020105, "点击dogtv是谁");
//                IS_DOGTV=true;
//                loading1.setVisibility(View.VISIBLE);
//                mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
//                mediaPlay.stop();
//                mediaPlay.reset();
//                mediaPlay.setOnPreparedListener(MainActivity.this);
//                String URL_DOG="http://cdn.wanbatv.com/dogtv/welcome.TS";
//                try {
//                    mediaPlay.setDataSource(URL_DOG);
//                    mediaPlay.prepareAsync();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
////            mediaPlay.setDataSource("http://121.201.7.173:8080/wangwang_sh/resource/play/Play_0002_MPEG4_4-3_720x576_2000000bps.MP4");
//
//            }
//        });
//        faq_iv=(FocusImageView)findViewById(R.id.faq_iv);
//        faq_iv.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Behavior.onEvent(MainActivity.this, 3020106, "点击FAQ");
//                creatAlertDialog6();
//            }
//        });

//        mian_title_iv=(ImageView)findViewById(R.id.mian_title_iv);

        zonghe_iv=(FocusImageView)findViewById(R.id.zonghe_iv);
        xiuxian_iv=(FocusImageView)findViewById(R.id.xiuxian_iv);
        yundong_iv=(FocusImageView)findViewById(R.id.yundong_iv);
        zhanshi_iv=(FocusImageView)findViewById(R.id.zhanshi_iv);
        zonghe_iv1=(FocusImageView)findViewById(R.id.zonghe_iv1);
        xiuxian_iv1=(FocusImageView)findViewById(R.id.xiuxian_iv1);
        yundong_iv1=(FocusImageView)findViewById(R.id.yundong_iv1);
        zhanshi_iv1=(FocusImageView)findViewById(R.id.zhanshi_iv1);
        if(Login2Activity.DOGTV_NUM==1){
            zonghe_iv1.setVisibility(View.VISIBLE);
            zonghe_iv.requestFocus();
        }else if(Login2Activity.DOGTV_NUM==2){
            xiuxian_iv1.setVisibility(View.VISIBLE);
            xiuxian_iv.requestFocus();
        }
        else if(Login2Activity.DOGTV_NUM==3){
            yundong_iv1.setVisibility(View.VISIBLE);
            yundong_iv.requestFocus();
        }
        else if(Login2Activity.DOGTV_NUM==4){
            zhanshi_iv1.setVisibility(View.VISIBLE);
            zhanshi_iv.requestFocus();
        }
        zonghe_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Behavior.onEvent(MainActivity.this, 3020101, "点击综合");
                IS_DOGTV=false;
                loading1.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
                PINGDAO_NUM=1;
                deleteiv();
                zonghe_iv1.setVisibility(View.VISIBLE);
                xiuxian_iv.setVisibility(View.VISIBLE);
                yundong_iv.setVisibility(View.VISIBLE);
                zhanshi_iv.setVisibility(View.VISIBLE);
                zonghe_iv1.requestFocus();
                mediaPlay.stop();
                mediaPlay.reset();


                url="http://121.201.7.173:8087/api/wangwangba/programs/category/0";


//                try {
//                    mediaPlay.setOnPreparedListener(MainActivity.this);
//                    mediaPlay.setDataSource(MainActivity.this, Uri.parse("http://121.201.7.173:8080/wangwang_sh/resource/play/" +
//                            "Play_0002_MPEG4_4-3_720x576_2000000bps.MP4"));
//                    mediaPlay.prepareAsync();
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
            }
        });
        xiuxian_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Behavior.onEvent(MainActivity.this, 3020103, "点击休闲");
                IS_DOGTV=false;
                loading1.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
                PINGDAO_NUM=2;

                deleteiv();
                zonghe_iv.setVisibility(View.VISIBLE);
                xiuxian_iv1.setVisibility(View.VISIBLE);
                yundong_iv.setVisibility(View.VISIBLE);
                zhanshi_iv.setVisibility(View.VISIBLE);
                xiuxian_iv1.requestFocus();
                mediaPlay.stop();
                mediaPlay.reset();
//                try {
//                    mediaPlay.setOnPreparedListener(MainActivity.this);
//                    mediaPlay.setDataSource(MainActivity.this, Uri.parse("http://121.201.7.173:8080/wanba_shzg/video/bbt/binfenwutai.mpg"));
//                    mediaPlay.prepareAsync();
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/1";
                RequestQueue rq = Volley.newRequestQueue(MainActivity.this.getApplicationContext());
                JsonObjectRequest request = new JsonObjectRequest(url, null,
                        new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    JSONObject objs=jsonObject.getJSONObject("data");
                                    JSONArray arr=objs.getJSONArray("list");
                                    for (int i=0;i<arr.length();i++){
                                        JSONObject arr_obj=arr.getJSONObject(i);
                                        list.add(arr_obj);
                                    }
                                    BOFANG_NUM=suijishu(list.size() -1);
//                                    JSONObject obj=arr.getJSONObject(BOFANG_NUM);
                                    JSONObject obj=list.get(BOFANG_NUM);
                                    String url_team2=obj.getString("content_name");
                                    long time=System.currentTimeMillis();
                                    final String shijianchuo=Long.toHexString(time);
                                    final String key="w2nBa7VS1";
                                    String url_key=key+url_team2+shijianchuo;
                                    String key_1=string2MD5(url_key);
                                    String url_team3=obj.getString("token");
                                    String url_team=url_qian+url_team3+"?auth_token="+key_1+"&auth_time="+shijianchuo;
                                    content_code=obj.getInt("content_code");
                                    content_name=obj.getString("content_name");
                                    try {
                                        mediaPlay.setOnPreparedListener(MainActivity.this);
                                        mediaPlay.setDataSource(url_team);
//            mediaPlay.setDataSource("http://121.201.7.173:8080/wangwang_sh/resource/play/Play_0002_MPEG4_4-3_720x576_2000000bps.MP4");
                                        mediaPlay.prepareAsync();
                                        list.remove(BOFANG_NUM);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    mediaPlay.setOnCompletionListener(MainActivity.this);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                }

                );
                rq.add(request);
            }
        });
        yundong_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Behavior.onEvent(MainActivity.this, 3020102, "点击运动");
                IS_DOGTV=false;
                loading1.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
                PINGDAO_NUM=3;

                deleteiv();
                zonghe_iv.setVisibility(View.VISIBLE);
                xiuxian_iv.setVisibility(View.VISIBLE);
                yundong_iv1.setVisibility(View.VISIBLE);
                zhanshi_iv.setVisibility(View.VISIBLE);
                yundong_iv1.requestFocus();
                mediaPlay.stop();
                mediaPlay.reset();
//                try {
//                    mediaPlay.setOnPreparedListener(MainActivity.this);
//                    mediaPlay.setDataSource(MainActivity.this, Uri.parse("http://121.201.7.173/video/9.m3u8"));
//                    mediaPlay.prepareAsync();
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/2";
                RequestQueue rq = Volley.newRequestQueue(MainActivity.this.getApplicationContext());
                JsonObjectRequest request = new JsonObjectRequest(url, null,
                        new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    JSONObject objs=jsonObject.getJSONObject("data");
                                    JSONArray arr=objs.getJSONArray("list");
                                    for (int i=0;i<arr.length();i++){
                                        JSONObject arr_obj=arr.getJSONObject(i);
                                        list.add(arr_obj);

                                    }
                                    BOFANG_NUM=suijishu(list.size()-1);
//                                    JSONObject obj=arr.getJSONObject(BOFANG_NUM);
                                    JSONObject obj=list.get(BOFANG_NUM);
                                    String url_team2=obj.getString("content_name");
                                    long time=System.currentTimeMillis();
                                    final String shijianchuo=Long.toHexString(time);
                                    final String key="w2nBa7VS1";
                                    String url_key=key+url_team2+shijianchuo;
                                    String key_1=string2MD5(url_key);
                                    String url_team3=obj.getString("token");
                                    String url_team=url_qian+url_team3+"?auth_token="+key_1+"&auth_time="+shijianchuo;
                                    content_code=obj.getInt("content_code");
                                    content_name=obj.getString("content_name");
                                    try {
                                        mediaPlay.setOnPreparedListener(MainActivity.this);
                                        mediaPlay.setDataSource(url_team);
//            mediaPlay.setDataSource("http://121.201.7.173:8080/wangwang_sh/resource/play/Play_0002_MPEG4_4-3_720x576_2000000bps.MP4");
                                        mediaPlay.prepareAsync();
                                        list.remove(BOFANG_NUM);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    mediaPlay.setOnCompletionListener(MainActivity.this);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {

                    }
                }

                );
                rq.add(request);
            }
        });
        zhanshi_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Behavior.onEvent(MainActivity.this, 3020104, "点击展示");
                IS_DOGTV=false;
                loading1.setVisibility(View.VISIBLE);
                mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
                PINGDAO_NUM = 4;
                deleteiv();
                zonghe_iv.setVisibility(View.VISIBLE);
                xiuxian_iv.setVisibility(View.VISIBLE);
                yundong_iv.setVisibility(View.VISIBLE);
                zhanshi_iv1.setVisibility(View.VISIBLE);
                zhanshi_iv1.requestFocus();
                mediaPlay.stop();
                mediaPlay.reset();
//                try {
//                    mediaPlay.setOnPreparedListener(MainActivity.this);
//                    mediaPlay.setDataSource(MainActivity.this, Uri.parse("http://121.201.7.173:8080/wanba_shzg/video/bbt/binfenwutai.mpg"));
//                    mediaPlay.prepareAsync();
//
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
                url = "http://121.201.7.173:8087/api/wangwangba/programs/category/3";
                RequestQueue rq = Volley.newRequestQueue(MainActivity.this.getApplicationContext());
                JsonObjectRequest request = new JsonObjectRequest(url, null,
                        new Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject jsonObject) {
                                try {
                                    JSONObject objs = jsonObject.getJSONObject("data");
                                    JSONArray arr = objs.getJSONArray("list");
                                    for (int i=0;i<arr.length();i++){
                                        JSONObject arr_obj=arr.getJSONObject(i);
                                        list.add(arr_obj);
                                    }

                                    BOFANG_NUM=suijishu(list.size()-1);



//                                    JSONObject obj=arr.getJSONObject(BOFANG_NUM);
                                    JSONObject obj=list.get(BOFANG_NUM);
                                    String url_team2=obj.getString("content_name");
                                    long time=System.currentTimeMillis();
                                    final String shijianchuo=Long.toHexString(time);
                                    final String key="w2nBa7VS1";
                                    String url_key=key+url_team2+shijianchuo;
                                    String key_1=string2MD5(url_key);
                                    String url_team3=obj.getString("token");
                                    String url_team=url_qian+url_team3+"?auth_token="+key_1+"&auth_time="+shijianchuo;
                                    content_code=obj.getInt("content_code");
                                    content_name=obj.getString("content_name");
                                    try {
                                        mediaPlay.setOnPreparedListener(MainActivity.this);
                                        mediaPlay.setDataSource(url_team);
//            mediaPlay.setDataSource("http://121.201.7.173:8080/wangwang_sh/resource/play/Play_0002_MPEG4_4-3_720x576_2000000bps.MP4");
                                        mediaPlay.prepareAsync();
                                        list.remove(BOFANG_NUM);

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    mediaPlay.setOnCompletionListener(MainActivity.this);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                    }
                }

                );
                rq.add(request);
            }
        });
        daiji_iv=(ImageView)findViewById(R.id.daiji_iv);


        mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);
        mHandler.sendEmptyMessage(MSG_UP_DOWN);

    }
    public void deleteiv(){
        zonghe_iv1.setVisibility(View.GONE);
        xiuxian_iv1.setVisibility(View.GONE);
        yundong_iv1.setVisibility(View.GONE);
        zhanshi_iv1.setVisibility(View.GONE);
    }





    private void creatAlertDialog_tuichu() {

        myDialog = new AlertDialog.Builder(this).create();

        myDialog.show();

        myDialog.getWindow().setContentView(R.layout.diolag_tuichu);

        myDialog.getWindow()
                .findViewById(R.id.no_iv)
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {

                        myDialog.dismiss();

                    }

                });



    }
    public void exitapp(){
        finish();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onPrepared(MediaPlayer mp) {
        mp.start();
        if (PINGDAO_NUM == 1) {
            Behavior.onPlayContentStart(MainActivity.this,101,"综合",content_code,content_name);
        }
        else  if(PINGDAO_NUM==2){
            Behavior.onPlayContentStart(MainActivity.this,103,"休闲",content_code,content_name);
        }
        else  if(PINGDAO_NUM==3){
            Behavior.onPlayContentStart(MainActivity.this,102,"运动",content_code,content_name);
        }
        else  if(PINGDAO_NUM==4){
            Behavior.onPlayContentStart(MainActivity.this,104,"展示",content_code,content_name);
        }
        else{
            Behavior.onPlayContentStart(MainActivity.this,106,"默认",content_code,content_name);

        }
        mHandler.sendEmptyMessage(PLAY_MESSAGE);
        daiji_iv.setVisibility(View.GONE);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
//        BOFANG_NUM=0;
//        if(BOFANG_NUM==1) {
//            Toast.makeText(MainActivity.this, "aaa", Toast.LENGTH_SHORT).show();
//            mediaPlay.reset();
//            try {
//                mediaPlay.setOnPreparedListener(this);
//                mediaPlay.setDataSource(MainActivity.this, Uri.parse("http://121.201.7.173:8080/wanba_shzg/video/bbt/binfenwutai.mpg"));
//                mediaPlay.prepareAsync();
//                mediaPlay.setOnCompletionListener(this);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//        else if(BOFANG_NUM==2){
//            Toast.makeText(MainActivity.this, "bbb", Toast.LENGTH_SHORT).show();
//            mediaPlay.reset();
//            try {
//                mediaPlay.setOnPreparedListener(this);
//                mediaPlay.setDataSource(MainActivity.this, Uri.parse("http://121.201.7.173/video/9.m3u8"));
//                mediaPlay.prepareAsync();
//                mediaPlay.setOnCompletionListener(this);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }else {
//
//        }3
        if (PINGDAO_NUM == 1) {
            Behavior.onPlayContentStop(MainActivity.this, 101, "综合", content_code, content_name);
        }
        else  if(PINGDAO_NUM==2){
            Behavior.onPlayContentStop(MainActivity.this, 103, "休闲", content_code, content_name);
        }
        else  if(PINGDAO_NUM==3){
            Behavior.onPlayContentStop(MainActivity.this, 102, "运动", content_code, content_name);
        }
        else  if(PINGDAO_NUM==4){
            Behavior.onPlayContentStop(MainActivity.this, 104, "展示", content_code, content_name);
        }
        else{
            Behavior.onPlayContentStop(MainActivity.this, 106, "默认", content_code, content_name);

        }

    loading1.setVisibility(View.VISIBLE);
        mHandler.sendEmptyMessage(MSG_PLAY_PROGRESS);

        if(IS_DOGTV){
            mediaPlay.reset();
            mediaPlay.setOnPreparedListener(MainActivity.this);
            String URL_DOG="http://cdn.wanbatv.com/dogtv/welcome.TS";
            try {
                mediaPlay.setDataSource(URL_DOG);
                mediaPlay.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            list.remove(BOFANG_NUM);
            RequestQueue rq = Volley.newRequestQueue(MainActivity.this.getApplicationContext());
            JsonObjectRequest request = new JsonObjectRequest(url, null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            try {
                                JSONObject objs=jsonObject.getJSONObject("data");
                                JSONArray arr=objs.getJSONArray("list");
//                            if(BOFANG_NUM<arr.length()){
                                if(list.size()>0) {
                                    BOFANG_NUM = suijishu(list.size() - 1);
                                }else{
                                    for (int i=0;i<arr.length();i++){
                                        JSONObject arr_obj=arr.getJSONObject(i);
                                        list.add(arr_obj);
                                    }
                                    BOFANG_NUM=suijishu(list.size() - 1);
//                                    JSONObject obj=arr.getJSONObject(BOFANG_NUM);

                                }

//                            }else{
//                                BOFANG_NUM=0;
//                            }
                                JSONObject obj=list.get(BOFANG_NUM);
                                String url_team2=obj.getString("content_name");
                                long time=System.currentTimeMillis();
                                final String shijianchuo=Long.toHexString(time);
                                final String key="w2nBa7VS1";
                                String url_key=key+url_team2+shijianchuo;
                                String key_1=string2MD5(url_key);
                                String url_team3=obj.getString("token");
                                String url_team=url_qian+url_team3+"?auth_token="+key_1+"&auth_time="+shijianchuo;
                                mediaPlay.reset();
                                content_code=obj.getInt("content_code");
                                content_name=obj.getString("content_name");
                                try {
                                    mediaPlay.setOnPreparedListener(MainActivity.this);
                                    mediaPlay.setDataSource(url_team);
//            mediaPlay.setDataSource("http://121.201.7.173:8080/wangwang_sh/resource/play/Play_0002_MPEG4_4-3_720x576_2000000bps.MP4");
                                    mediaPlay.prepareAsync();
                                    mediaPlay.setOnCompletionListener(MainActivity.this);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            }

            );
            rq.add(request);
        }
    }


    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        mediaPlay=new MediaPlayer();
        mediaPlay.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlay.setDisplay(surfaceholder);
//        if (PINGDAO_NUM == 1) {
//            url="http://121.201.7.173:8087/api/wangwangba/programs/category/0";
//        }
//        else  if(PINGDAO_NUM==2){
//            url="http://121.201.7.173:8087/api/wangwangba/programs/category/1";
//        }
//        else  if(PINGDAO_NUM==3){
//            url="http://121.201.7.173:8087/api/wangwangba/programs/category/2";
//        }
//        else  if(PINGDAO_NUM==4){
//            url="http://121.201.7.173:8087/api/wangwangba/programs/category/3";
//        }else{
            if(Login2Activity.DOGTV_NUM==1){
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/0";
            }else if(Login2Activity.DOGTV_NUM==2){
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/1";
            }
            else if(Login2Activity.DOGTV_NUM==3){
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/2";
            }
            else if(Login2Activity.DOGTV_NUM==4){
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/3";
            }else{
                url="http://121.201.7.173:8087/api/wangwangba/programs/category/0";
            }



//        }


        RequestQueue rq = Volley.newRequestQueue(MainActivity.this.getApplicationContext());
        JsonObjectRequest request = new JsonObjectRequest(url, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject objs=jsonObject.getJSONObject("data");
                            JSONArray arr=objs.getJSONArray("list");
                            JSONObject obj=null;
                                if (list.size()==0) {
                                    for (int i=0;i<arr.length();i++){
                                        JSONObject arr_obj=arr.getJSONObject(i);
                                        list.add(arr_obj);
                                    }

                                    BOFANG_NUM=suijishu(list.size()-1);
                                    obj=list.get(BOFANG_NUM);
                                }else{
                                    BOFANG_NUM = suijishu(list.size() - 1);
                                    obj=list.get(BOFANG_NUM);
                                }

                            String url_team2=obj.getString("content_name");
                            long time=System.currentTimeMillis();
                            final String shijianchuo=Long.toHexString(time);
                            final String key="w2nBa7VS1";
                            String url_key=key+url_team2+shijianchuo;
                            String key_1=string2MD5(url_key);
                            String url_team3=obj.getString("token");
                            String url_team=url_qian+url_team3+"?auth_token="+key_1+"&auth_time="+shijianchuo;
                            content_code=obj.getInt("content_code");
                            content_name=obj.getString("content_name");
                            try {
                                mediaPlay.setOnPreparedListener(MainActivity.this);
                                mediaPlay.setDataSource(url_team);
//            mediaPlay.setDataSource("http://121.201.7.173:8080/wangwang_sh/resource/play/Play_0002_MPEG4_4-3_720x576_2000000bps.MP4");
                                mediaPlay.prepareAsync();

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            mediaPlay.setOnCompletionListener(MainActivity.this);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        }

        );
        rq.add(request);


    }


    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }


    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mediaPlay.release();
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {

//        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
//
//            creatAlertDialog_tuichu();
//            return true;
//        }
//        IS_DOWN=false;
//        if(main_lin_down.getVisibility()==View.GONE ){
//            if(keyCode==KeyEvent.KEYCODE_BACK){
//                return super.onKeyDown(keyCode, event);
//            }
//            else{
//                IS_DOWN=false;
//                main_lin_down.setVisibility(View.VISIBLE);
//                main_button_show.setVisibility(View.GONE);
//                main_button_down.requestFocus();
//            }
//        }
        return super.onKeyDown(keyCode, event);
    }


    public int suijishu(int num){
        Random random = new Random();
        int s = (int)(Math.random() * (num+1));
        return s;

    }
    public static String string2MD5(String inStr){
        MessageDigest md5 = null;
        try{
            md5 = MessageDigest.getInstance("MD5");
        }catch (Exception e){
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++){
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString().toLowerCase();

    }
    @Override
    protected void onResume() {
        super.onResume();
        Behavior.onPageResume(this,200001,"进入汪星人频道");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Behavior.onPagePause(this, 200001, "退出汪星人频道");
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (PINGDAO_NUM == 1) {
            Behavior.onPlayContentStop(MainActivity.this, 101, "综合", content_code, content_name);
        }
        else  if(PINGDAO_NUM==2){
            Behavior.onPlayContentStop(MainActivity.this, 103, "休闲", content_code, content_name);
        }
        else  if(PINGDAO_NUM==3){
            Behavior.onPlayContentStop(MainActivity.this, 102, "运动", content_code, content_name);
        }
        else  if(PINGDAO_NUM==4){
            Behavior.onPlayContentStop(MainActivity.this, 104, "展示", content_code, content_name);
        }
        else{
            Behavior.onPlayContentStop(MainActivity.this,106,"默认",content_code,content_name);

        }
    }
}
